package com.ccjk.beusoft.thirdlib.plugin1.hook.handler;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.ccjk.beusoft.thirdlib.StubActivity;
import com.ccjk.beusoft.thirdlib.plugin1.PluginManager1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import static com.ccjk.beusoft.thirdlib.plugin1.hook.Hook.KEY_REAL_ACTIVITY;

/**
 * Created by CCJK on 2017/12/20.
 */

public class ActivityManagerHook implements InvocationHandler {
    private final Context context;
    Object originIActivityManager;

    public ActivityManagerHook(Context context, Object originIActivityManager) {
        this.context = context;
        this.originIActivityManager = originIActivityManager;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Log.e("ActivityManagerHook", Thread.currentThread().getName() + " : " + method.getName());
        if (TextUtils.equals("startActivity", method.getName())) {
            try {
                Intent rawIntent = (Intent) args[2];
                if (!PluginManager1.get().isHost(rawIntent.getPackage())) {//如果不是宿主程序的activity
                    //从这知道，插件中的隐式启动不支持
                    Intent newIntent = new Intent();
                    newIntent.setClass(context, StubActivity.class);
                    newIntent.putExtra(KEY_REAL_ACTIVITY, rawIntent);
                    args[2] = newIntent;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return method.invoke(originIActivityManager, args);
    }
}
